package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIORunnable;
import com.vrv.app.cyberspace.common.ddio.TemplateMessage;
import com.vrv.app.cyberspace.common.utils.HttpContextUtils;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.common.utils.ToolUtil;
import com.vrv.app.cyberspace.config.WXBSystemConfig;
import com.vrv.app.cyberspace.modules.sys.entity.*;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.IEventFeedbackTableService;
import com.vrv.app.cyberspace.modules.sys.service.IEventManageTableService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-21
 */
@SuppressWarnings({"Duplicates", "SpringJavaInjectionPointsAutowiringInspection"})
@Service
@Transactional
public class EventFeedbackTableServiceImpl extends ServiceImpl<EventFeedbackTableMapper, EventFeedbackTable> implements IEventFeedbackTableService {
    Logger logger = Logger.getLogger(EventFeedbackTableServiceImpl.class);

    @Autowired
    private EventFeedbackTableMapper eventFeedbackTableMapper;
    @Autowired
    private IEventManageTableService eventManageTableService;
    @Autowired
    private OrganizeTableMapper organizeTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private CirculationRecordTableMapper circulationRecordTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;
    @Autowired
    private EventTypeTableMapper eventTypeTableMapper;
    @Autowired
    private WXBSystemConfig wxbSystemConfig;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Override
    public Integer submitEventFeedback(EventFeedbackTable eventFeedbackTable) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        Date date = new Date();
        eventFeedbackTable.setUserID(userTable.getLinkdoodID());
        eventFeedbackTable.setUpdateTime(date);
        if (1 == eventFeedbackTable.getStatus()) {//插入记录
            eventFeedbackTable.setExStatus(-1);
            insertRecord(eventFeedbackTable, userTable, date);
        }
        return eventFeedbackTableMapper.updateById(eventFeedbackTable);
    }

    private void insertRecord(EventFeedbackTable eventFeedbackTable, UserTable userTable, Date date) {
        CirculationRecordTable circulationRecordTable = new CirculationRecordTable();
        circulationRecordTable.setTime(date);
        circulationRecordTable.setOperator(userTable.getLinkdoodName());
        circulationRecordTable.setContent(JSON.toJSONString(eventFeedbackTable));
        circulationRecordTable.setfId(eventFeedbackTable.getId());
        circulationRecordTableMapper.insert(circulationRecordTable);
    }

    @Override
    public EventFeedbackTable detailEventFeedback(EventFeedbackTable eft) {
        //1.根据ID获取Event_Feedback表中记录
        EventFeedbackTable eventFeedbackTable = eventFeedbackTableMapper.selectById(eft.getId());
        //2.更新查看状态
        UserTable readUser = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        eventFeedbackTable.setReadUserID(readUser.getLinkdoodID());
        eventFeedbackTable.setReadTime(new Date());
        eventFeedbackTableMapper.updateById(eventFeedbackTable);
        //3.返回详情
        eventFeedbackTable.setEventManageTable(eventManageTableService.getEventExtend(eventFeedbackTable.getBaseID()));
        eventFeedbackTable.setReadUser(readUser);
        if (eventFeedbackTable.getUserID() != null)
            eventFeedbackTable.setHandleUser(userTableMapper.selectById(eventFeedbackTable.getUserID()));
        //4.共下发多少家,反馈/未反馈数据量
        List<String> list = JSON.parseArray(eventFeedbackTable.getDownsSet(), String.class);
        if (list != null && list.size() > 0) {
            eventFeedbackTable.setTotalNum(list.size());
            eventFeedbackTable.setFeedbackNum(eventFeedbackTableMapper.selectCount(new EntityWrapper<EventFeedbackTable>()
                    .eq("baseID", eventFeedbackTable.getBaseID())
                    .in("orgID", list)
                    .eq("status", 1)));
        }
        return eventFeedbackTable;
    }

    @Override
    public Page<EventFeedbackTable> listEventFeedback(EventFeedbackTable feedbackTable, Page<EventFeedbackTable> page) {
        List<EventFeedbackTable> eventFeedbackTableList = new ArrayList<>();
        if (feedbackTable.getStatus() != null) {
            eventFeedbackTableList = eventFeedbackTableMapper.selectPage(page, new EntityWrapper<EventFeedbackTable>().eq("orgID", feedbackTable.getOrgID())
                    .eq("status", feedbackTable.getStatus()).orderBy(true, "createTime", false));
        }
        if (feedbackTable.getStatusList() != null) {//此逻辑是为了支持前端传递多个status进行查询--同时不改变PC端的逻辑
            List<Integer> statusList = JSON.parseArray(feedbackTable.getStatusList(), Integer.class);
            eventFeedbackTableList = eventFeedbackTableMapper.selectPage(page, new EntityWrapper<EventFeedbackTable>().eq("orgID", feedbackTable.getOrgID())
                    .in("status", statusList).orderBy(true, "status").orderBy(true, "createTime", false));
        }

        for (EventFeedbackTable e : eventFeedbackTableList) {
            e.setEventManageTable(eventManageTableService.getEventExtend(e.getBaseID()));
            if (e.getReadUserID() != null)
                e.setReadUser(userTableMapper.selectById(e.getReadUserID()));
            if (e.getUserID() != null)
                e.setHandleUser(userTableMapper.selectById(e.getUserID()));
        }
        page.setRecords(eventFeedbackTableList);
        return page;
    }

    @Override
    public Page<EventFeedbackTable> summary(EventFeedbackTable eventFeedbackTable, Page<EventFeedbackTable> page) {
        List<String> orgIDs = JSON.parseArray(eventFeedbackTable.getDownsSet(), String.class);
        Wrapper<EventFeedbackTable> ew = new EntityWrapper<EventFeedbackTable>()
                .eq("baseID", eventFeedbackTable.getBaseID())
                .in("orgID", orgIDs);
        List<EventFeedbackTable> list = eventFeedbackTableMapper.selectPage(page, ew);
        OrganizeTable organization;
        for (EventFeedbackTable e : list) {
            organization = organizeTableMapper.selectById(e.getOrgID());
            if (organization != null)
                e.setOrgName(organization.getOrgName());
            e.setHandleUser(userTableMapper.selectById(e.getUserID()));
            e.setReadUser(userTableMapper.selectById(e.getReadUserID()));
        }
        return page.setRecords(list);
    }

    @Override
    public JSONResult releaseEvent(EventFeedbackTable eft) {
        JSONResult jsonResult = JSONResult.renderSuccess();
        //1.根据OrgID查询组织下的人员
        try {
            List<String> orgIDs = JSONArray.parseArray(eft.getDownsSet(), String.class);
            if (orgIDs != null && orgIDs.size() > 0) {
                List<UserTable> list = userTableMapper.selectList(new EntityWrapper<UserTable>().in("orgID", orgIDs));
                List<String> toUsers = new ArrayList<>();
                for (UserTable u : list) {
                    toUsers.add(u.getLinkdoodID());
                }

                EventFeedbackTable tem = eventFeedbackTableMapper.selectById(eft.getId());
                //2.创建反馈表
                EventFeedbackTable eventFeedback = new EventFeedbackTable();
                eventFeedback.setBaseID(tem.getBaseID());
                eventFeedback.setCreateTime(new Date());
                for (String orgid : ToolUtil.removeDuplInList(orgIDs)) {
                    eventFeedback.setOrgID(orgid);
                    eventFeedbackTableMapper.insert(eventFeedback.clone());
                }
                //3.记录下发单位
                tem.setDownsSet(eft.getDownsSet());
                tem.setReplyClaim(eft.getReplyClaim());
                eventFeedbackTableMapper.updateById(tem);
                //4.推送模板消息
                pushTemplateMessage(tem, toUsers);
            }
        } catch (CloneNotSupportedException e) {
            jsonResult = JSONResult.renderError();
            e.printStackTrace();
        }
        return jsonResult;
    }

    @Override
    public JSONResult handleEventFeedback(EventFeedbackTable eventFeedbackTable) {
        EventFeedbackTable tem = eventFeedbackTableMapper.selectById(eventFeedbackTable.getId());
        tem.setStatus(eventFeedbackTable.getStatus());
        return eventFeedbackTableMapper.updateById(tem) > 0 ? JSONResult.renderSuccess() : JSONResult.renderError();
    }

    private void pushTemplateMessage(EventFeedbackTable eft, List<String> toUsers) {
        String appid = apiV2Service.getAppID();
        EventManageTable emt = eventManageTableService.selectById(eft.getBaseID());
        EventTypeTable firstEventType = eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst());
        EventTypeTable secondEventType = eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond());
        String content = "时间: " + dateFormat.format(new Date()) + "\n标题：" + emt.getTitle() + "\n类别: " + firstEventType.getName() + "-" + secondEventType.getName() + "\n请您及时处理 ";
        TemplateMessage templateMessage = TemplateMessage.createOne(appid, "事件管理", appid, content, wxbSystemConfig.getEventFeedbackDetailUrl() + "&id=" + emt.getBaseID(),
                StringUtils.join(toUsers.toArray(), ','));
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送事件管理(ID" + emt.getBaseID() + ")消息失败! ");
            e.printStackTrace();
        }
    }

}
